<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\yb\ExchangeableModel;
use App\Models\yb\UserModel;
use Illuminate\Http\Request;

class ExchangeableController extends Controller
{

    /**
     * Get a JWT via given credentials.
     *  发布易换
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){

        $openid = $request->post('openid');
        $user_data = UserModel::where(['openid'=>$openid])->first();

        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $content = $request->post('content');

        if(empty($content)){
            return response()->json(['code'=>'203','msg' => '内容不能为空']);
        }

        ExchangeableModel::insert([
            'user_id'=>$user_data['id'],
            'openid'=>$openid,
            'content'=>$content,
            'created_at'=>date('Y-m-d H:i:s',time())
        ]);

        return response()->json(['code'=>'200','msg' => '请求成功']);

    }

    /**
     * Get a JWT via given credentials.
     *  易换列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function listing(Request $request)
    {
        $openid = $request->post('openid');

        $user_data = UserModel::where(['openid'=>$openid])->first();
        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $page = $request->post('page', 1);

        $take = $request->post('take', 10);

        $data = ExchangeableModel::orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();
        foreach($data as $key=>$val){
            $user_data = UserModel::where(['openid'=>$val['openid']])->first();
            $data[$key]['avatar'] = $user_data['avatar'];
        }

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);

    }

}
